package com.qyhl.school.school.reporter.contribution;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.gyf.immersionbar.ImmersionBar;
import com.luck.picture.lib.tools.ScreenUtils;
import com.qyhl.school.R;
import com.qyhl.school.R2;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.MPermissionUtils;
import com.qyhl.webtv.basiclib.utils.NetUtil;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.school.SchoolContributionBean;
import com.qyhl.webtv.commonlib.utils.MShareBoard;
import com.qyhl.webtv.commonlib.utils.share.ShareUtils;
import com.weavey.loading.lib.LoadingLayout;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import butterknife.BindView;
import butterknife.OnClick;

@Route(path = ARouterPathConstant.SCHOOL_REPORTER_CONTRIBUTION_DETAIL)
public class SchoolContributionActivity extends BaseActivity implements SchoolContributionContract.SchoolContributionView {
    @BindView(R2.id.scan_num)
    TextView scanNum;
    @BindView(R2.id.title)
    TextView title;
    @BindView(R2.id.school_name)
    TextView schoolName;
    @BindView(R2.id.writer)
    TextView writer;
    @BindView(R2.id.webView)
    WebView webView;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;

    @Autowired(name = "id")
    int id;

    private SchoolContributionBean mBean;

    private SchoolContributionPresenter mPresenter;

    @Override
    protected int getContentView() {
        return R.layout.activity_school_reporter_contribution;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        mImmersionBar.statusBarColor(R.color.white).statusBarDarkFont(true).fitsSystemWindows(true).init();

    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        loadMask.setStatus(LoadingLayout.Loading);

        mPresenter = new SchoolContributionPresenter(this);

        initWebView();

        mPresenter.getDetail(id);
    }

    @Override
    protected void setListener() {
        loadMask.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                loadMask.setReloadButtonText("加载中...");
                mPresenter.getDetail(id);
            }
        });
    }

    private void singleShare(String style) {
        try {
            MPermissionUtils.requestPermissionsResult(SchoolContributionActivity.this, 1, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, new MPermissionUtils.OnPermissionListener() {
                @Override
                public void onPermissionGranted() {
                    ShareUtils.getInstance().goSingleShare(style, mBean.getId() + "", 42, mBean.getWriter(), mBean.getTitle(), mBean.getLogo(), SchoolContributionActivity.this);
                }

                @Override
                public void onPermissionDenied() {
                    MPermissionUtils.showTipsDialog(SchoolContributionActivity.this);
                }
            });
        } catch (Exception e) {
            showToast(e.getMessage());
        }

    }

    /**
     * 初始化webview
     */
    @SuppressLint("JavascriptInterface")
    private void initWebView() {
        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(false);
        settings.setDefaultTextEncodingName("utf-8");
        settings.setDomStorageEnabled(true);
        settings.setBlockNetworkImage(false);//是否阻塞加载网络图片  协议http or https
        settings.setUseWideViewPort(false);
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        settings.setSupportZoom(false);
        settings.setBuiltInZoomControls(false);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
    }

    @OnClick({R2.id.back_btn, R2.id.share_btn, R2.id.share_wechat, R2.id.share_circle, R2.id.share_qq})
    public void onClick(View view) {
        int viewId = view.getId();
        if (viewId == R.id.back_btn) {
            finish();
        } else if (viewId == R.id.share_btn) {
            if (mBean != null) {
                MPermissionUtils.requestPermissionsResult(SchoolContributionActivity.this, 1, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, new MPermissionUtils.OnPermissionListener() {
                    @Override
                    public void onPermissionGranted() {
                        MShareBoard shareBoard = new MShareBoard(SchoolContributionActivity.this, mBean.getId() + "", mBean.getTitle(), mBean.getLogo(), mBean.getWriter(), 42, false);
                        shareBoard.showPopupWindow();
                    }

                    @Override
                    public void onPermissionDenied() {
                        MPermissionUtils.showTipsDialog(SchoolContributionActivity.this);
                    }
                });
            }
        } else if (viewId == R.id.share_wechat) {
            singleShare("WeiXin");
        } else if (viewId == R.id.share_circle) {
            singleShare("Circle");
        } else if (viewId == R.id.share_qq) {
            singleShare("QQ");
        }
    }

    @Override
    public void setDetail(SchoolContributionBean bean) {
        loadMask.setReloadButtonText("点击重试~");
        loadMask.setStatus(LoadingLayout.Success);

        mBean = bean;

        title.setText(bean.getTitle());

        scanNum.setText(StringUtils.transformNum(bean.getHitCount() + ""));

        schoolName.setText(bean.getSchool());

        writer.setText(bean.getWriter());

        String htmlString = getNewContent(bean.getContent());
        webView.loadDataWithBaseURL(null, htmlString, "text/html", "utf-8", null);
        webView.setWebViewClient(mWebViewClient);
    }

    @Override
    public void setError(String msg) {
        loadMask.setReloadButtonText("点击重试~");
        loadMask.setStatus(LoadingLayout.Error);
        if (!NetUtil.isNetworkAvalible(this)) {
            loadMask.setErrorImage(R.drawable.error_network);
            loadMask.setErrorText("网络异常，请检查您的网络！");
        } else if (msg.contains("暂无")) {
            loadMask.setErrorImage(R.drawable.empty_content);
            loadMask.setErrorText(msg);
        } else {
            loadMask.setErrorImage(R.drawable.error_content);
            loadMask.setErrorText(msg);
        }
    }

    //webview中的图片自适应大小
    private String getNewContent(String htmlText) {
        Document document = Jsoup.parse(htmlText);
        Elements pElements = document.select("p:has(img)");
        for (Element pElement : pElements) {
            pElement.attr("style", "text-align:center");
            pElement.attr("max-width", String.valueOf(ScreenUtils.getScreenWidth(this) + "px"))
                    .attr("height", "auto");
        }
        Elements imgElements = document.select("img");
        for (Element imgElement : imgElements) {
            //重新设置宽高
            imgElement.attr("max-width", "100%")
                    .attr("height", "auto");
            imgElement.attr("style", "max-width:100%;height:auto");
        }
        return document.toString();
    }

    private WebViewClient mWebViewClient = new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url.startsWith("http:") || url.startsWith("https:")) {
                try {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(intent);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                return false;
            }

            return true;
        }


        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);

            //这个是一定要加上那个的,配合scrollView和WebView的height=wrap_content属性使用
            int w = View.MeasureSpec.makeMeasureSpec(0,
                    View.MeasureSpec.UNSPECIFIED);
            int h = View.MeasureSpec.makeMeasureSpec(0,
                    View.MeasureSpec.UNSPECIFIED);
            //重新测量
            webView.measure(w, h);

        }
    };
}
